package com.ja.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.servlet.http.HttpServletRequest;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.springframework.web.context.ContextLoader;

import com.ja.domain.Admin;
import com.ja.domain.Liushui;
import com.ja.domain.RedPacket;
import com.ja.domain.User;
import com.ja.sevice.BackManagerService;
import com.ja.sevice.RedPacketService;
import com.ja.sevice.impl.UserServiceImpl;
import com.ja.util.RedPacketUtil;
/**
 * <style>*{font-size: 14px;font-weight: bold;}div{height:28px;margin-bottom:-23px;}img {position: fixed;bottom: 10px;right: 10px;height: 50px;}span{border: 3px solid blue;color: white;background: blue;display: inline-block;box-shadow: 2px 2px gray;margin: 2px 10px;margin-left: 40px;}l div{font-size:40px;display: inline-block;line-height: 16px;position: absolute;margin-top: -3px;font-weight: lighter;color: red;}p{font-weight: lighter;margin-top: 22px;}l{display: inline-block;width: 80px;text-align: right;color: black;margin-top:10px;}</style><img src="https://a3.qpic.cn/psb?/V13i62Dj12ePbQ/NZmahM6aAmswZqIzVUkRHAvJMKUvnBP*ccASpf*fwec!/m/dF4BAAAAAAAAnull&bo=zwGhAAAAAAADB00!&rf=photolist&t=5"></img><div class="me" style="margin-top:-26px;">
 * <p><b>　描述：</b><!--TODO-->群聊控制层
 * </p><l>INFO<div>☞</div></l><span>文件名：ChatController3.java　　　版本：v1.0
 * </span><br><l>Date<div>☞</div></l><span>2018年3月21日 下午12:02:18
 * </span><br><l>Author<div>☞</div></l><span>Bean
 * </span></div>
 */
@ServerEndpoint("/all1")
public class ChatController4{
	
	private RedPacketService redPacketService = (RedPacketService) ContextLoader.getCurrentWebApplicationContext().getBean("redPacketService");
	
	private UserServiceImpl userService = (UserServiceImpl) ContextLoader.getCurrentWebApplicationContext().getBean("userService");
	
	private BackManagerService managerService=(BackManagerService)ContextLoader.getCurrentWebApplicationContext().getBean("managerService");
	
    private static int onlineCount = 0;
   
    private static CopyOnWriteArraySet<ChatController4> webSocketSet = new CopyOnWriteArraySet<ChatController4>();
    
    private static List<String> names= new ArrayList<String>();
    //将联系人通道和联系人同时保存
    static Map<String, Session> map=new HashMap<String, Session>();
    private Session session;
    private String name;
	public static Long midTime14;
	public static int num = 0;
    
	@Override
	public String toString() {
		return "ChatController3 [name=" + name + "]";
	}

	/**
     * 连接建立成功调用的方法
     * @param session  可选的参数。session为与某个客户端的连接会话，需要通过它来给客户端发送数据
     */
    @OnOpen
    public void onOpen(Session session){
        this.session = session;
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        this.name= session.getRequestParameterMap().get("name").get(0);//获取本次登录用户的姓名
        names.add(this.name);//将本次登录用户的姓名添加到names里面
        map.put(name, session);
//        ChatController3 tr = new ChatController3(); 
//        Thread t=new Thread(tr);
//        if (isFirst) {
//        	isFirst=false;
//        	t.start();
//		}
//        this.run();
    }
     
    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose(){
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1    
//        System.out.println("有一连接关闭！当前在线人数为" + getOnlineCount());
    }
     
    /**
     * 收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     * @param session 可选的参数
     */
    private static boolean isFirst=true;
	@OnMessage
    public void onMessage(String message1, Session session,HttpServletRequest request) {
    	if (isFirst) {
    			isFirst=false;
    			while (true) {
    				if(num==1){
    				try {
    					Admin admin = managerService.inquireAll();
    					long time = Long.parseLong(admin.getTime());//间隔
    					midTime14 = time/1000;
    					Double jine = Double.parseDouble(admin.getRedenvelopes());//金额
    					String type = admin.getTypeofredenvelopes();//类型
    					String message = admin.getLeavingamessage();//留言
    					int geshu = admin.getNumberofredpackets();//个数
    					
    					String x="";
    					if (type.contains("普通")) {
    						List<Integer> list=RedPacketUtil.splitRedPackets((int) (jine*10.0), geshu);
    						x=list.toString().replace("[", "").replace("]", "").replace(" ", "");
    						type="拼手气红包";
    						userService.updBlance(0,jine);
    					}else {
    						userService.updBlance(0,Double.parseDouble(geshu*(new Double(jine)).intValue()+""));
    						for (int i = 0; i < geshu; i++) {
    							x+=(((new Double(jine)).intValue()*10)+",");
    						}
    						x=x.substring(0, x.length()-1);
    					}
    					RedPacket redPacket=new RedPacket(0, new SimpleDateFormat("yyyy/MM/dd HH:mm:ss").format(new Date()), type, jine+"", geshu+"", message, x, 0);
    					redPacketService.insert(redPacket);
    					User byid = userService.getUserByid(0);
    					User user= new User();
    					user.setId(0);
    					Liushui l=null;
    					if (type.contains("普通")) {
    						user.setBalance(byid.getBalance()-jine);
    						l=new Liushui(byid.getName(), "红包扣除", byid.getBalance(), jine, user.getBalance(), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), "", "", "", "", "红包扣除", false, 1, byid.getId());
    					}else {
    						user.setBalance(byid.getBalance()-jine*Double.parseDouble(geshu+""));
    						l=new Liushui(byid.getName(), "红包扣除", byid.getBalance(), jine*Double.parseDouble(geshu+""), user.getBalance(), new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()), "", "", "", "", "红包扣除", false, 1, byid.getId());
    					}
    					
    					userService.updateMoney(user, l);
    					int redPackId=redPacket.getId();
    					for (ChatController4 item : webSocketSet) {
    						item.sendMessage("11BeanRedPackageJa1BeanRedPackageJa"+message+"BeanRedPackageJa"+type+"BeanRedPackageJa"+redPackId+"k45jk459fgjdf986kjh98fgdkj3i45y89fdh4598hp90u0"+"k45jk459fgjdf986kjh98fgdkj3i45y89fdh4598hp90u"+time);
    					}
//    				this.sendMessage("恭喜潘**一分时时彩201803050639期第二球1中奖168.10k45jk459fgjdf986kjh98fgdkj3i45y89fdh4598hp90u"+0);
//    					Thread.sleep(time);
    					while (midTime14>0) {
    						midTime14--;
    						long hh = midTime14 / 60 / 60 % 60;
    						long mm = midTime14 / 60 % 60;
    						long ss = midTime14 % 60;
    						System.out.println("还剩"+hh+"小时"+mm+"分钟"+ss+"秒");
    						try {
    							Thread.sleep(1000);
    						} catch (InterruptedException e) {
    							e.printStackTrace();
    						}
    					}
    				} catch (Exception e) {
    					e.printStackTrace();
    				}
    			}else{
    				midTime14=0l;
    				for (ChatController4 item : webSocketSet) {
						item.sendMessage("BeanRedPackageJa0");
					}
    				try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
    			}
    		}
		}
	}
    
    
    /**
     * 发生错误时调用
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error){
        System.out.println("发生错误111");
//        error.printStackTrace();
    }
    /**
     * 这个方法与上面几个方法不一样。没有用注解，是根据自己需要添加的方法。
     * @param message
     * @throws IOException
     */
    public void sendMessage(String message){
    	try {
			this.session.getBasicRemote().sendText(message);
		} catch (Exception e) {
		}
    }
    
    public void sendMessageToPeople(String toName,String fromName,String message) throws IOException {
    	this.session.getBasicRemote().sendText(toName+fromName+message);
	}
    
    
 
    public static synchronized int getOnlineCount() {
        return onlineCount;
    }
 
    public static synchronized void addOnlineCount() {
        ChatController4.onlineCount++;
    }
     
    public static synchronized void subOnlineCount() {
        ChatController4.onlineCount--;
    }

}